package com.wafer.server;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 
 * @Package: com.wafer.server 
 * @author: bw   
 * @date: 2018年4月25日 上午10:02:13 
 * @todo: TODO
 */
public class DynaticTcpServer {

	private Integer port;
	
	private ServerSocket serverSocket;
	
	public DynaticTcpServer(final Integer port) {
		this.port = port;
		init();
	}
	
	/**
	 * 初始化serverSocket
	 */
	private void init() {
		try {
			   serverSocket = new ServerSocket(port);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 监听端口, 当有新的连接创建新的线程保持连接。
	 */
	public void doWork() {
		ExecutorService threadPool = Executors.newFixedThreadPool(3);  // 提供固定线程池
        while(true) {
    		try {
			      Socket socket = serverSocket.accept();
			      System.out.println("有新的连接:" + socket.getInetAddress().getHostAddress() + ":" +socket.getPort());
			      threadPool.execute(new ServerThread(socket));
		} catch (IOException e) {
			e.printStackTrace();
		} 
      }
	}

}
